//
//  NSString+Extension.m
//  SinaRadio
//
//  Created by lina on 11-11-29.
//  Copyright (c) 2011年 Sina. All rights reserved.
//

#import "NSString+Extension.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString ( Extension )

- (NSString *) md5
{
    const char* str = [self UTF8String];    
    unsigned char result[16];    
    CC_MD5(str, strlen(str), result);        
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",            result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],            result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]            ];
}

- (NSString*) urlEncoding
{	
    NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);	
    return [result autorelease];
}

- (NSString*) convertToTime
{
    NSString* time;
	NSCalendar* calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
	
	static NSDateFormatter* dateFormatter = nil;
	if (dateFormatter == nil) {
		dateFormatter = [[NSDateFormatter alloc] init];
	}
    //	NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    double dd = [self doubleValue];
    NSDate* createdAt = [NSDate dateWithTimeIntervalSince1970:dd];
    NSDateComponents *nowComponents = [calendar components:unitFlags fromDate:[NSDate date]];
    NSDateComponents *createdAtComponents = [calendar components:unitFlags fromDate:createdAt];
	if([nowComponents year] == [createdAtComponents year] &&
       [nowComponents month] == [createdAtComponents month] &&
       [nowComponents day] == [createdAtComponents day])
    {//今天
		
		int time_long = [createdAt timeIntervalSinceNow];
		
		if (time_long <= 0 && time_long >-60*60) {//一小时之内
			int min = -time_long/60;
			if (min == 0) {
				min = 1;
			}
            //			time = [[[NSString alloc]initWithFormat:loadMuLanguage(@"%d分钟前",@""),min] autorelease];
			if (min <= 1) {
				time = [NSString stringWithFormat:@" %d分钟前",min];
			} else {
				time = [NSString stringWithFormat:@"%d分钟前",min];				
			}
		}else if (time_long > 0) {
			time = [NSString stringWithFormat:@" %d分钟前",1];
            
		} else {
			[dateFormatter setDateFormat:@"'今天 'HH:mm"];
            
			time = [dateFormatter stringFromDate:createdAt];
		}
    } else if ([nowComponents year] == [createdAtComponents year]) {
		NSLocale *cnLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
		[dateFormatter setLocale:cnLocale];
		[cnLocale release];
		[dateFormatter setDateFormat:@"MM-dd' 'HH:mm"];
		time = [dateFormatter stringFromDate:createdAt];
	} else {//去年
		NSLocale *cnLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
		[dateFormatter setLocale:cnLocale];
		[cnLocale release];
		[dateFormatter setDateFormat:@"YYYY-MM-dd' 'HH:mm"];
		time = [dateFormatter stringFromDate:createdAt];		
    }
    [calendar release];
    //	[dateFormatter release];
	
    return time;
}

- (NSString*) convertToTimeHead
{
    NSString* time;
	NSCalendar* calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
	NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
	
    
    double dd = [self doubleValue];
    NSDate* createdAt = [NSDate dateWithTimeIntervalSince1970:dd];
    NSDateComponents *nowComponents = [calendar components:unitFlags fromDate:[NSDate date]];
    NSDateComponents *createdAtComponents = [calendar components:unitFlags fromDate:createdAt];
	if([nowComponents year] == [createdAtComponents year] &&
       [nowComponents month] == [createdAtComponents month] &&
       [nowComponents day] == [createdAtComponents day])
    {//今天
		[dateFormatter setDateFormat:@"'今天 'HH:mm"];
		
		time = [dateFormatter stringFromDate:createdAt];
		
    } else if ([nowComponents year] == [createdAtComponents year]) {
		NSLocale *cnLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
		[dateFormatter setLocale:cnLocale];
		[cnLocale release];
        //		[dateFormatter setDateFormat:loadMuLanguage(@"MMMMd'日 'HH:mm",@"")];
		[dateFormatter setDateFormat:@"MM.dd' 'HH:mm"];
		time = [dateFormatter stringFromDate:createdAt];
	} else {//去年
		NSLocale *cnLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
		[dateFormatter setLocale:cnLocale];
		[cnLocale release];
		[dateFormatter setDateFormat:@"YYYY.MM.dd' 'HH:mm"];
		time = [dateFormatter stringFromDate:createdAt];		
    }
    [calendar release];
    [dateFormatter release];
	
    return time;
}

- (int) calculateTextNumber
{	
    // Source: http://www.cocoachina.com/macdev/cocoa/2011/0110/2552.html    
    int i, n = [self length], l = 0, a = 0, b = 0;	    
    unichar c;	    
    for(i = 0; i < n; i++)
    {		        
        c = [self characterAtIndex:i];		        
        if (isblank(c)) 
        {           
            b++;        
        } else if (isascii(c)) 
        {            
            a++;        
        } 
        else 
        {			
            l++;        
        }    
    }	    
    if(a == 0 && l == 0) return 0;	    
    return l+(int)ceilf((float)(a+b)/2.0);
}

- (NSString *) htmlEntityDecoding
{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"<",@"&lt;",@">",@"&gt;",@"\"",@"quot;",@"&",@"&amp",@" ",@"&nbsp;" ,nil];
    NSArray * array = [dic allKeys];
    NSString * htmlStr = self;
    for (NSString * aStr in array ) 
    {
        htmlStr = [htmlStr stringByReplacingOccurrencesOfString:aStr withString:[dic objectForKey:aStr]];
    }
    
    return htmlStr;
}

- (NSString *) htmlImgPath
{
    NSBundle * bundle = [NSBundle mainBundle];
    NSString *  resPath = [bundle resourcePath];
    resPath = [resPath stringByAppendingPathComponent:self];
   
    resPath = [resPath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    resPath = [resPath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
    resPath = [NSString stringWithFormat:@"file:/%@//",resPath];
    return resPath;
}

@end
